package com.example.pei.ithinklearnt.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.ImageShowAdapter;
import com.example.pei.ithinklearnt.view.customview.savePhotoDialog;
import com.github.piasy.biv.BigImageViewer;
import com.github.piasy.biv.loader.fresco.FrescoImageLoader;

import java.io.File;
import java.util.List;
import java.util.UUID;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;


//点击某一张图片显示的大图，由于比较简单，就不用MVP了，，，
public class FrescoLoaderPicturesActivity extends AppCompatActivity implements View.OnClickListener {


    private ViewPager viewPager;  //对应的viewPager
    private ImageShowAdapter mImageShowAdapter;
    private TextView textView_shownum;

    private ImageButton imageButton_back;
    private ImageButton imageButton_choose;
    private savePhotoDialog mSavePhotoDialog;

    private List<String> list;  //图片的Url

    private int currentPosition; //当前页面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fresco_loader_pictures);
        BigImageViewer.initialize(FrescoImageLoader.with(getApplicationContext()));
        findWidgets();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ib_back:
                finish();
                break;
            case R.id.ib_choose:
                chooseDownloadPhoto();
                break;
        }
    }

    private void findWidgets(){
        viewPager =  findViewById(R.id.viewpagerrr);
        textView_shownum=findViewById(R.id.tv_shownum);
        imageButton_back=findViewById(R.id.ib_back);
        imageButton_choose=findViewById(R.id.ib_choose);

        imageButton_back.setOnClickListener(this);
        imageButton_choose.setOnClickListener(this);

        Intent intent=getIntent();


        list =intent.getStringArrayListExtra("photoUris");
        if(list.size()<=1){
            textView_shownum.setVisibility(View.GONE);
        }
        final int currentPage=intent.getIntExtra("currentPage",0);
        currentPosition=currentPage;

        mImageShowAdapter=new ImageShowAdapter(list,FrescoLoaderPicturesActivity.this);
        viewPager.setAdapter(mImageShowAdapter);
        viewPager.setCurrentItem(currentPage);
        textView_shownum.setText((currentPage+1)+"/"+list.size());
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
            @Override public void onPageScrollStateChanged(int state) {}
            @Override
            public void onPageSelected(int position) {
                textView_shownum.setText((position+1)+"/"+list.size());
                currentPosition=position;
            }
        });
    }

    public void chooseDownloadPhoto(){
        View vieww = getLayoutInflater().inflate(R.layout.save_photo_dialog, null);
        mSavePhotoDialog=new savePhotoDialog(FrescoLoaderPicturesActivity.this, R.style.transparentFrameWindowStyle, new savePhotoDialog.PhotoSaveListener() {
            @Override
            public void onClick(View view) {
                downLoadPhoto();
                mSavePhotoDialog.dismiss();
            }
        });
        mSavePhotoDialog.setContentView(vieww, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
        Window window = mSavePhotoDialog.getWindow();
        // 设置显示动画
        //   window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        // wl.y = (getWindowManager().getDefaultDisplay().getHeight());
        wl.gravity = Gravity.CENTER;
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // mSavePhotoDialog.getWindow().setAttributes(wl);

        // 设置显示位置
        mSavePhotoDialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        mSavePhotoDialog.setCanceledOnTouchOutside(true);
        mSavePhotoDialog.show();
    }

    private void downLoadPhoto() {
        String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/woxiangxue/";
        String fileName1 = UUID.randomUUID().toString();

        BmobFile file = new BmobFile(fileName1 + ".jpg", "", list.get(currentPosition));
        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
        final File saveFile = new File(dir, file.getFilename());
        file.download(saveFile, new DownloadFileListener() {
            @Override
            public void onStart() {
                Toast.makeText(FrescoLoaderPicturesActivity.this, "正在保存", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void done(String savePath, BmobException e) {
                if (e == null) {
                    Uri uri = Uri.fromFile(saveFile);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                    Toast.makeText(FrescoLoaderPicturesActivity.this, "已保存到"+savePath, Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(FrescoLoaderPicturesActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onProgress(Integer value, long newworkSpeed) {
            }
        });
    }
}
